package edu.ynu.se.xiecheng.achitectureclass.controller;

import edu.ynu.se.xiecheng.achitectureclass.dto.CaptureWithSensorDataResponse;
import edu.ynu.se.xiecheng.achitectureclass.dto.SensorDataResponse;
import edu.ynu.se.xiecheng.achitectureclass.entity.CameraCapture;
import edu.ynu.se.xiecheng.achitectureclass.service.CameraService;
import edu.ynu.se.xiecheng.achitectureclass.service.SensorDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "摄像头接口")
@Slf4j
@RestController
@RequestMapping("/api/camera")
@RequiredArgsConstructor
@CrossOrigin(origins = "http://localhost:5173", allowedHeaders = {"Authorization", "Content-Type"}, methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
public class CameraController {
    private final CameraService cameraService;
    private final SensorDataService sensorDataService;
    
    @ApiOperation("抓拍照片并获取传感器数据")
    @PostMapping("/capture-with-sensors")
    public ResponseEntity<Map<String, Object>> captureWithSensorData(
            @RequestParam(required = false) Integer quality) {
        log.info("开始抓拍照片并获取传感器数据，质量级别: {}", quality);
        
        try {
            CameraCapture capture = cameraService.captureImage(quality);
            List<SensorDataResponse> sensorDataList = sensorDataService.getGreenhouseSensorData();
            
            CaptureWithSensorDataResponse responseData = new CaptureWithSensorDataResponse();
            responseData.setCapture(capture);
            responseData.setSensorDataList(sensorDataList);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", responseData);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("抓拍失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "抓拍失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    @ApiOperation("获取抓拍记录")
    @GetMapping("/captures")
    public ResponseEntity<Map<String, Object>> getCaptures() {
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "success");
        response.put("data", cameraService.getLastWeekCaptures());
        return ResponseEntity.ok(response);
    }
    
    @ApiOperation("获取摄像头信息")
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getCameraInfo() {
        log.info("获取摄像头信息");
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "success");
        response.put("data", cameraService.getCameraInfo());
        return ResponseEntity.ok(response);
    }
    
    @ApiOperation("获取最近一周的抓拍记录")
    @GetMapping("/captures/week")
    public ResponseEntity<Map<String, Object>> getLastWeekCaptures() {
        Map<String, Object> response = new HashMap<>();
        List<Map<String, Object>> capturesWithSensorData = new ArrayList<>();
        
        try {
            List<CameraCapture> captures = cameraService.getLastWeekCaptures();
            log.info("找到 {} 条抓拍记录", captures.size());
            
            // 对每个抓拍记录，获取对应时间点的传感器数据
            for (CameraCapture capture : captures) {
                Map<String, Object> captureData = new HashMap<>();
                
                log.info("处理抓拍记录: id={}, time={}, url={}", 
                    capture.getId(), capture.getCaptureTime(), capture.getPicUrl());
                
                // 从数据库获取该时间点的传感器数据
                List<Map<String, Object>> historicalData = sensorDataService.getDataByTime(capture.getCaptureTime());
                
                // 构建响应数据
                Map<String, Object> data = new HashMap<>();
                data.put("picUrl", capture.getPicUrl());
                data.put("captureTime", capture.getCaptureTime());
                data.put("quality", capture.getQuality());
                data.put("sensorData", historicalData);
                
                captureData.put("code", "200");
                captureData.put("msg", "success");
                captureData.put("data", data);
                
                capturesWithSensorData.add(captureData);
            }
            
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", capturesWithSensorData);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取抓拍记录失败", e);
            response.put("code", 500);
            response.put("message", "获取抓拍记录失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    @ApiOperation("获取萤石云访问令牌")
    @GetMapping("/token")
    public ResponseEntity<Map<String, Object>> getYingshiToken() {
        log.info("获取萤石云访问令牌");
        try {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", cameraService.getCameraToken());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取萤石云token失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "获取萤石云token失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}
